package com.pay.utils.http;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


/**
 * http 公共类
 *
 * @author MENG
 * @version 2018/7/5
 * @see
 */
public class HttpClientUtils
{
    static Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);

    public static String httpRequest(String url, String requestMethod, Map<String, String> paramsMap)
    {
        List<BasicNameValuePair> formparams = new ArrayList<BasicNameValuePair>();

        //post json没有试过
        if ("post".equals(requestMethod.toLowerCase()))
        {
            HttpPost httppost = new HttpPost(url);

            httppost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

//            httppost.setHeader("Content-Type", "application/json;charset=utf-8");

            for (Iterator<String> it = paramsMap.keySet().iterator(); it.hasNext();)
            {
                String key = it.next();

                String value = paramsMap.get(key);

                formparams.add(new BasicNameValuePair(key, value));
            }

            return doRequest(httppost, null, formparams);
        }
        else if ("get".equals(requestMethod.toLowerCase()))
        {
            HttpGet httppost = new HttpGet(url);

            for (Iterator<String> it = paramsMap.keySet().iterator(); it.hasNext();)
            {
                String key = it.next();

                String value = paramsMap.get(key);

                formparams.add(new BasicNameValuePair(key, value));
            }

            return doRequest(null, httppost, formparams);
        }

        return "";
    }

    private static String doRequest(HttpPost httpPost, HttpGet httpGet, List<BasicNameValuePair> formparams)
    {
        String str = "";

        try
        {
            CloseableHttpResponse response = null;

            UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(formparams,"UTF-8");

            // 设置请求和传输超时时间
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(25000).setConnectTimeout(30000)
                .build();

            if (null != httpPost)
            {
                httpPost.setEntity(uefEntity);

                httpPost.setConfig(requestConfig);

                response = HttpClientPool.getHttpClient().execute(httpPost);

            }
            else
            {
                httpGet.setConfig(requestConfig);

                response = HttpClientPool.getHttpClient().execute(httpGet);

            }

            HttpEntity entity = response.getEntity();

            str = EntityUtils.toString(entity, "UTF-8");

            if (null == str || "".equals(str))
            {
                return "";

            }
        }
        catch (Exception e)
        {
            logger.error("http application/x-www-form-urlencoded 请求执行错误!",e);
        }

        return str;
    }

    public static  String httpJsonPost(String url,String json)
    {

        CloseableHttpResponse response = null;

        HttpPost httppost = new HttpPost(url);

        // 得指明使用UTF-8编码，否则到API服务器XML的中文不能被成功识别
        StringEntity postEntity = new StringEntity(json, "UTF-8");

        httppost.addHeader("Content-Type", "application/json;charset=utf-8");

        httppost.setEntity(postEntity);

        // 设置请求和传输超时时间
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(25000).setConnectTimeout(3000)
            .build();

        String str = "";

        try
        {
            response = HttpClientPool.getHttpClient().execute(httppost);

            HttpEntity entity = response.getEntity();

            str = EntityUtils.toString(entity, "UTF-8");

            if (null == str || "".equals(str))
            {
                return "";

            }
        }
        catch (IOException e)
        {
            logger.error("http application/json 请求执行错误!");
        }

        return str;
    }

}
